import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:xh_danmu/xh_danmu.dart';
import '../controllers/danmu_controller.dart';
import '../../../widgets/danmu_input.dart';

class DanmuView extends GetView<DanmuPageController> {
  const DanmuView({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color(0xFF0A0A0A),
      appBar: _buildAppBar(),
      body: Obx(() {
        if (!controller.isInitialized.value) {
          return const Center(
            child: CircularProgressIndicator(),
          );
        }

        return SingleChildScrollView(
          child: Column(
            children: [
              // 模式信息栏
              _buildModeInfo(),

              // 弹幕显示区域
              SizedBox(
                height: MediaQuery.of(context).size.height * 0.4,
                child: _buildDanmuArea(),
              ),

              // 控制区域
              _buildControlArea(),
            ],
          ),
        );
      }),
    );
  }

  /// 构建应用栏
  PreferredSizeWidget _buildAppBar() {
    return AppBar(
      title: Obx(() => Text(controller.currentModeDisplayName)),
      backgroundColor: Colors.black87,
      foregroundColor: Colors.white,
      elevation: 0,
      leading: IconButton(
        icon: const Icon(Icons.arrow_back),
        onPressed: () => Get.back(),
      ),
      actions: [
        // 设置菜单
        PopupMenuButton<String>(
          icon: const Icon(Icons.settings),
          onSelected: (value) => _handleMenuAction(value),
          itemBuilder: (context) => [
            PopupMenuItem(
              value: 'toggle_status',
              child: Obx(() => Row(
                    children: [
                      Icon(controller.showStatus.value ? Icons.visibility_off : Icons.visibility),
                      const SizedBox(width: 8),
                      Text(controller.showStatus.value ? '隐藏状态' : '显示状态'),
                    ],
                  )),
            ),
            PopupMenuItem(
              value: 'toggle_tracks',
              child: Obx(() => Row(
                    children: [
                      Icon(controller.showTrackBorders.value ? Icons.grid_off : Icons.grid_on),
                      const SizedBox(width: 8),
                      Text(controller.showTrackBorders.value ? '隐藏轨道' : '显示轨道'),
                    ],
                  )),
            ),
            PopupMenuItem(
              value: 'toggle_debug',
              child: Obx(() => Row(
                    children: [
                      Icon(controller.showDebugInfo.value ? Icons.bug_report : Icons.bug_report_outlined),
                      const SizedBox(width: 8),
                      Text(controller.showDebugInfo.value ? '隐藏调试' : '显示调试'),
                    ],
                  )),
            ),
            const PopupMenuItem(
              value: 'print_debug',
              child: Row(
                children: [
                  Icon(Icons.print),
                  SizedBox(width: 8),
                  Text('打印状态'),
                ],
              ),
            ),
          ],
        ),
      ],
    );
  }

  /// 处理菜单操作
  void _handleMenuAction(String action) {
    switch (action) {
      case 'toggle_status':
        controller.toggleStatus();
        break;
      case 'toggle_tracks':
        controller.toggleTrackBorders();
        break;
      case 'toggle_debug':
        controller.toggleDebugInfo();
        break;
      case 'print_debug':
        controller.printDebugStatus();
        break;
    }
  }

  /// 构建模式信息栏
  Widget _buildModeInfo() {
    return Container(
      width: double.infinity,
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        gradient: LinearGradient(
          colors: [
            _getModeColor().withOpacity(0.2),
            _getModeColor().withOpacity(0.1),
          ],
        ),
        border: Border(
          bottom: BorderSide(
            color: _getModeColor().withOpacity(0.3),
          ),
        ),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Container(
                padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                decoration: BoxDecoration(
                  color: _getModeColor(),
                  borderRadius: BorderRadius.circular(12),
                ),
                child: Text(
                  _getModeIcon(),
                  style: const TextStyle(fontSize: 16),
                ),
              ),
              const SizedBox(width: 12),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      controller.currentModeDisplayName,
                      style: const TextStyle(
                        color: Colors.white,
                        fontSize: 16,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    Text(
                      controller.currentModeDescription,
                      style: TextStyle(
                        color: Colors.white.withOpacity(0.7),
                        fontSize: 12,
                      ),
                    ),
                  ],
                ),
              ),
              // 统计信息
              Obx(() => Container(
                    padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
                    decoration: BoxDecoration(
                      color: Colors.black.withOpacity(0.3),
                      borderRadius: BorderRadius.circular(8),
                    ),
                    child: Text(
                      '发送: ${controller.sentCount.value}',
                      style: const TextStyle(
                        color: Colors.white,
                        fontSize: 12,
                      ),
                    ),
                  )),
            ],
          ),
        ],
      ),
    );
  }

  /// 获取模式颜色
  Color _getModeColor() {
    switch (controller.currentMode.value) {
      case DanmuMode.performance:
        return const Color(0xFF2196F3);
      case DanmuMode.custom:
        return const Color(0xFF9C27B0);
      case DanmuMode.debug:
        return const Color(0xFFFF9800);
      default:
        return const Color(0xFF4CAF50);
    }
  }

  /// 获取模式图标
  String _getModeIcon() {
    switch (controller.currentMode.value) {
      case DanmuMode.performance:
        return '⚡';
      case DanmuMode.custom:
        return '🎨';
      case DanmuMode.debug:
        return '🔧';
      default:
        return '🎬';
    }
  }

  /// 构建弹幕显示区域
  Widget _buildDanmuArea() {
    return Container(
      margin: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        gradient: const LinearGradient(
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
          colors: [
            Color(0xFF1A1A2E),
            Color(0xFF16213E),
            Color(0xFF0F3460),
          ],
        ),
        borderRadius: BorderRadius.circular(16),
        border: Border.all(color: Colors.white.withOpacity(0.2)),
        boxShadow: [
          BoxShadow(
            color: _getModeColor().withOpacity(0.3),
            blurRadius: 20,
            offset: const Offset(0, 10),
          ),
        ],
      ),
      child: ClipRRect(
        borderRadius: BorderRadius.circular(15),
        child: Stack(
          children: [
            // 主弹幕组件
            XhDanmuWidget(
              controller: controller.danmuController,
              config: controller.danmuConfig,
              background: _buildBackground(),
            ),

            // 调试组件（按需显示）
            Obx(() {
              if (!controller.showTrackBorders.value && !controller.showDebugInfo.value) {
                return const SizedBox.shrink();
              }

              return Stack(
                children: [
                  // 轨道边界
                  if (controller.showTrackBorders.value)
                    XhDanmuTrackBorders(
                      controller: controller.danmuController,
                      borderColor: _getModeColor().withOpacity(0.5),
                      showLabels: true,
                    ),

                  // 调试信息
                  if (controller.showDebugInfo.value)
                    XhDanmuDebugInfo(
                      controller: controller.danmuController,
                      backgroundColor: Colors.black.withOpacity(0.8),
                    ),
                ],
              );
            }),
          ],
        ),
      ),
    );
  }

  /// 构建背景
  Widget _buildBackground() {
    return Container(
      decoration: BoxDecoration(
        gradient: LinearGradient(
          begin: Alignment.center,
          end: Alignment.bottomCenter,
          colors: [
            Colors.transparent,
            Colors.black.withOpacity(0.1),
          ],
        ),
      ),
      child: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text(
              _getModeIcon(),
              style: const TextStyle(fontSize: 48),
            ),
            const SizedBox(height: 16),
            Text(
              controller.currentModeDisplayName,
              textAlign: TextAlign.center,
              style: const TextStyle(
                color: Colors.white38,
                fontSize: 20,
                fontWeight: FontWeight.w300,
              ),
            ),
            const SizedBox(height: 8),
            Text(
              controller.currentModeDescription,
              textAlign: TextAlign.center,
              style: const TextStyle(
                color: Colors.white24,
                fontSize: 14,
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// 构建控制区域
  Widget _buildControlArea() {
    return Container(
      padding: const EdgeInsets.all(16),
      child: Column(
        children: [
          // 弹幕输入（使用新的Stream架构）
          DanmuInputWidget(
            streamController: controller.streamController,
            hintText: '输入弹幕内容（Stream模式）...',
            onSent: () {
              controller.sentCount.value++;
            },
          ),

          const SizedBox(height: 16),

          // 控制按钮（使用新的Stream控制）
          DanmuControlWidget(
            controller: controller.danmuController,
            streamController: controller.streamController,
          ),

          const SizedBox(height: 16),

          // 快速测试按钮
          _buildQuickActions(),

          const SizedBox(height: 16),

          // WebSocket模拟器
          WebSocketSimulatorWidget(
            streamController: controller.streamController,
          ),

          // 状态显示
          Obx(() {
            if (!controller.showStatus.value) {
              return const SizedBox.shrink();
            }

            return Padding(
              padding: const EdgeInsets.only(top: 16),
              child: XhDanmuDetailedStatus(
                controller: controller.danmuController,
                showTrackDetails: true,
              ),
            );
          }),
        ],
      ),
    );
  }

  /// 构建控制按钮
  Widget _buildControlButtons() {
    return XhDanmuControlPanel(
      controller: controller.danmuController,
      customButtons: [
        // 状态按钮
        Obx(() => ElevatedButton.icon(
              onPressed: controller.toggleStatus,
              icon: Icon(
                controller.showStatus.value ? Icons.info : Icons.info_outline,
                size: 16,
              ),
              label: const Text('状态', style: TextStyle(fontSize: 12)),
              style: ElevatedButton.styleFrom(
                backgroundColor: controller.showStatus.value ? Colors.purple : Colors.purple.withOpacity(0.6),
                foregroundColor: Colors.white,
                padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
              ),
            )),

        // 自动发送按钮（性能测试模式）
        if (controller.currentMode.value == DanmuMode.performance)
          Obx(() => ElevatedButton.icon(
                onPressed: controller.toggleAutoSend,
                icon: Icon(
                  controller.autoSendEnabled.value ? Icons.stop : Icons.play_arrow,
                  size: 16,
                ),
                label: Text(
                  controller.autoSendEnabled.value ? '停止' : '自动',
                  style: const TextStyle(fontSize: 12),
                ),
                style: ElevatedButton.styleFrom(
                  backgroundColor: controller.autoSendEnabled.value ? Colors.red : Colors.green,
                  foregroundColor: Colors.white,
                  padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
                ),
              )),
      ],
    );
  }

  /// 构建快速操作
  Widget _buildQuickActions() {
    return Container(
      padding: const EdgeInsets.all(12),
      decoration: BoxDecoration(
        color: Colors.white.withOpacity(0.1),
        borderRadius: BorderRadius.circular(8),
      ),
      child: Column(
        children: [
          const Text(
            '快速测试',
            style: TextStyle(
              color: Colors.white,
              fontSize: 14,
              fontWeight: FontWeight.bold,
            ),
          ),
          const SizedBox(height: 8),
          Wrap(
            spacing: 8,
            runSpacing: 8,
            alignment: WrapAlignment.center,
            children: [
              _buildQuickButton('简单文本', () => controller.sendTestDanmu()),
              _buildQuickButton('VIP弹幕', () => controller.sendVipDanmu()),
              _buildQuickButton('礼物弹幕', () => controller.sendGiftDanmu()),
              _buildQuickButton('系统通知', () => controller.sendSystemNotice()),
              if (controller.currentMode.value == DanmuMode.performance) ...[
                _buildQuickButton('10条', () => controller.sendBatchDanmu(10)),
                _buildQuickButton('20条', () => controller.sendBatchDanmu(20)),
              ],
              _buildQuickButton('清空', () => controller.clearAllDanmu()),
            ],
          ),
        ],
      ),
    );
  }

  /// 构建快速按钮
  Widget _buildQuickButton(String label, VoidCallback onPressed) {
    return ElevatedButton(
      onPressed: onPressed,
      style: ElevatedButton.styleFrom(
        backgroundColor: _getModeColor().withOpacity(0.7),
        foregroundColor: Colors.white,
        padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
        minimumSize: const Size(60, 32),
        textStyle: const TextStyle(fontSize: 11),
      ),
      child: Text(label),
    );
  }
}
